import Util from '../../utils/util.js';
import Status from "../../utils/status";
import {getParkList, getShopList} from "../../api/shop";
import {getBannerData} from "../../api/api";
import {updateMemberPark} from "../../api/member";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: {},
    cartTotal: {},
    categoryList: [],

    isFixed: false,

    cartDialog: false,
    menuDailog: false,
    showParkDialog: false, //园区选择

    tabCurrent: 0,
    topHeight: 60,
    // topHeight: 330, //顶部高度
    curIndex: 0,
    isload: false,

    menus: [],
    indicatorDots: true,
    circular: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    imgUrls: [],

    navs: [
      {title: "园区新鲜事", link: "/pages/category/index?id=11",},
      {title: "福利中心", link: "/pages/shop/gift",},
      // {title: "商家入驻", link: "/pages/supplier/form",},
      {title: "意见反馈", link: "/pages/advice/index",},
    ],

    tags: [
      "综合排序",
      "特惠商品",
      "预订单",
      "早餐供应",
    ],

    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    et_show: true,
    lists: [],

    parks: [],

    park_idx: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let tabbars = Status.tabbarMenus()
    if (tabbars.length == 3) {
      this.setData({
        tabCurrent: 1
      })
    }

    const that = this;
    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20,
      isload: true,
      shop_supplier_id: wx.getStorageSync('shop_supplier_id'),
      current_date: Util.formatTime(3) + " " + Util.getWeek(),
      currentWeek: Util.getWeek(),
      currentDay: Util.formatTime(4),
      park_id: wx.getStorageSync("park_id"),
      park_title: wx.getStorageSync("park_title"),
    });

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      wx.hideLoading()

      that.setData({
        userInfo: res.userInfo,
        cartList: Util.getCartList(),
        isload: false
      })

      getParkList().then(res => {
        let parks = res.data.parks || [];

        that.setData({
          parks: parks,
        })
        let park_id = wx.getStorageSync("park_id"),
          park_title = "";

        if (park_id) {
          parks.map((e1, index) => {
            if (park_id == e1.id) {
              park_title = e1.title || ""
              return;
            }
          })
          if (!park_title) {
            park_id = parks[0].id || "";
            park_title = parks[0].title || "";
          }
        } else {
          park_id = parks[0].id || "";
          park_title = parks[0].title || "";
        }

        that.setData({
          park_id: park_id,
          park_title: park_title
        })

        wx.setStorageSync("park_id", park_id)
        wx.setStorageSync("park_title", park_title)

        if (park_id == 1 && (!that.data.userInfo.tags || that.data.userInfo.tags.length == 0)) {
          wx.redirectTo({
            url: "../member/tag"
          })
        }
      }).finally(() => {
        that.initData();
      })

      this.onLoadTabbar();
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.hideLoading();
    })
  },

  initData() {
    const that = this;
    getBannerData("index_slides").then((res) => {
      that.setData({
        imgUrls: res.data.banners || [],
        tipPath: res.data.tip_pic || null,
        tipTimes: res.data.tip_times || 1
      })

      let tipPath_times = wx.getStorageSync("tipPath_times") || 0;
      if (!Util.isEmpty(that.data.tipPath) && tipPath_times < that.data.tipTimes) {
        this.setData({
          showTipDialog: true,
          dialogContent: {
            dC1: "trans-image",
            topClose: true,
            // showIcon: false,
            title: " ",
            hideMaskClose: true,
            data: {
              type: "image",
              path: that.data.tipPath || ""
            }
          }
        })
        wx.setStorageSync("tipPath_times", tipPath_times + 1);
      }

    })

    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: [],
    })
    this.getLists()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  showParkDialog(e) {
    if (this.data.parks.length <= 1) {
      return Util.Tips({title: "暂无开放其他园区", hideMask: true});
    }
    this.setData({
      showParkDialog: !this.data.showParkDialog
    })
  },

  selectPark(e) {//选择园区
    this.setData({
      showParkDialog: false,
      park_idx: e.currentTarget.dataset.index,
      park_title: this.data.parks[e.currentTarget.dataset.index].title || "",
      park_id: e.currentTarget.dataset.id,
    })
    wx.setStorageSync("park_id", this.data.park_id);
    wx.setStorageSync("park_title", this.data.park_title);
    updateMemberPark({park_id: this.data.park_id}).then((res) => {
    })

    if (this.data.park_id == 1 && (!this.data.userInfo.tags || this.data.userInfo.tags.length == 0)) {
      wx.redirectTo({
        url: "../member/tag"
      })
    }
    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: [],
    })
    this.getLists()

  },
  getLists() {
    const that = this;
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});
    let filter = that.data.filter || {}
    filter['page_num'] = that.data.page;

    if (wx.getStorageSync("park_id"))
      filter['park_id'] = wx.getStorageSync("park_id");

    getShopList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = Util.SplitArray(list, lists);
      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        total: res.data.total,
        page: that.data.page + 1,
        et_show: lists.length > 0,
      });

      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      Util.Tips({title: errmsg, hideMask: true});
    })
  },

  onPageScroll: function (e) {

    if (e.scrollTop > 50) {
      this.setData({
        isFixed: true,
        showParkDialog: false
      })
    } else {
      this.setData({isFixed: false})
    }
  },

  goSwiper(e) {
    const tabbarMenus = Status.tabbarMenus(),
      userInfo = this.data.userInfo;
    let url = e.currentTarget.dataset.url,
      summary = e.currentTarget.dataset.summary;

    if (summary == 'znct') {
      let supplier_id = 10002;
      if (!Util.isEmpty(userInfo) && !Util.isEmpty(userInfo.tags) && userInfo.tags.indexOf(2) !== -1) {
        supplier_id = 10001;
      }
      wx.navigateToMiniProgram({
        appId: 'wxf01be12354b159d2',
        path: 'pages/index/index?ssid=' + supplier_id,
        success(res) {
        },
        fail(res) {
        }
      })

      return;
    }
    if (Util.isEmpty(url))
      return;


    let flag = false;
    tabbarMenus.forEach((e1, i) => {
      if (e1.pagePath == url) {
        wx.switchTab({
          url: e1.pagePath
        })
        flag = true;
      }
    })

    if (flag)
      return;

    wx.navigateTo({
      url: url
    })

    return true;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  onLoadTabbar() {//底部tabbar返回数据
    const that = this;
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
    }).then(() => {
      wx.createSelectorQuery().in(that).select('.navbar')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          that.setData({
            topHeight: rect.height || 80
          })
        }).exec()
    });
  },

  onTabItemTap(e) {
    const that = this;
    that.setData({
      bottom: parseInt(e.detail || 0)
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.initData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})